import Taro, { Component } from '@tarojs/taro'
import { View, Text, Image } from '@tarojs/components'
import { AtButton, AtList, AtListItem, AtActionSheet, AtTextarea } from 'taro-ui'
import { DNavBar, DUserlistBox, DModal, DAtInpute, Ddialog } from '@/components'
import classNames from 'classnames'
import './detail.scss'
import http from '@/api'
import common from '@/common/'
const countMinPri = common.countMinPri
import sdk from '@/common/sdk'

const icon_chat = require('../assets/icon_chat.png')
const icon_favorite = require('../assets/icon_favorite.png')
const icon_phone = require('../assets/icon_phone.png')
const icon_complaint = require('../../assets/images/icon-complaint@2x.png')
const icon_close = require('../../assets/images/icon-close@2x.png')

export default class DetailBox extends Component {

    constructor(props) {
        super(props)
        this.state = {
            showComplaint: false,
            tags: [
                {
                    text: '试探行情',
                    id: 1
                },
                {
                    text: '虚假寻车',
                    id: 2
                },
                {
                    text: '电话无法接听',
                    id: 3
                },
                {
                    text: '要价离谱',
                    id: 4
                },
                {
                    text: '其他',
                    id: 5
                },
            ],
            tagActives: [1],
            accContent: '企业账户未开通电子收款账户，将会影响企业收款，是否前往开通？',
            imIdStatus: '',
            showAccDialog: false,
            itemlist: [],
            dataList: {
                creatorContact: ''
            },
            isShow: false,
            status: '',
            id: "",
            active: '1', // 1: 我的寻车详情 2:寻车详情
            secondList: [],
            footerlist: [
                // {
                //     src: icon_chat,
                //     text: '私信',
                //     onhandle: this.handleInformation.bind(this)
                // },
                {
                    src: icon_phone,
                    text: '电话',
                    onhandle: this.onHandleFirst.bind(this)
                },
                // {
                //     src: icon_favorite,
                //     text: '收藏'
                // }
            ],
            isOpened: false,
            _objMoney: {
                money: "",
                moneyback: ""
            },
            itemtelphon: '13600053041',
            enterformstatus: 1, // 1:展示企业信息  2:隐藏
            enterform: {
                img: require('../assets/header.png')
            },
            statusHtml: false
        }
    }
    componentWillMount() {
        let { id = '0fee6f4a-1b59-458d-9cab-fb9d27f8aca9', status = '1', active = '1' } = this.$router.params
        this.getCarSearchDetail({ id: `${id}` })
        this.setState({
            status,
            id,
            active
        })
    }

    componentDidShow() {
        sdk.setTitleInfo('寻车详情')
    }

    // 私信
    handleInformation() {
        let { carIsHideContact } = this.state
        if (carIsHideContact === '1') {
            return Taro.showToast({
                title: '买家已隐藏联系方式',
                icon: 'none'
            })
        }
        if (window.bridge) {
            const { dataList } = this.state
            window.bridge.callHandler('IMChat', { 'tephone': dataList.creatorContact }, function responseCallback(res) { })
            sdk.setWechatInfo(dataList.creatorContact, 1, dataList.carDataModel)
        }
    }

    //获取数据
    getCarSearchDetail(id) {
        http.getCarSearchDetail(id).then(res => {
            if (!res) {
                return
            }
            let { itemlist, secondList, active, itemtelphon, enterformstatus } = this.state
            itemlist = []
            secondList = []
            res.quotedList.map((item, i) => {
                itemlist.push({
                    id: res.id,
                    qpid: item.id,
                    entId: item.entId,
                    entName: item.entName,
                    creatorId: item.creatorId,
                    creatorContact: item.creatorContact,
                    creator: item.creator,
                    title: `${item.creator}(${item.entDis})`,
                    money: `报价${item.qpPrice}万`,
                    open: false,
                    list: [
                        {
                            text: '企业名称',
                            name: `${item.entName}`
                        },
                        {
                            text: '手机号码',
                            name: `${item.creatorContact}`
                        },
                        {
                            text: '留言',
                            name: `${item.qpRemark}` || '--'
                        }
                    ]
                })
                secondList.push({
                    title: `${item.creator}(${item.entDis})`,
                    extraText: `报价${item.qpPrice}万`
                })
            })

            // let creatorId = ''
            // if (localStorage.getItem('userInformation')) {
            //     let { dsfUserEntity = '' } = JSON.parse(localStorage.getItem('userInformation'))
            //     creatorId = dsfUserEntity.userId
            // }
            // if (creatorId && creatorId !== res.creatorId) {
            //     active = '2'
            // }
            if (res.isQuotedPrice === '1') {
                active = '2'
            } else {
                active = '1'
            }
            if (res.carIsHideContact === '1') {
                enterformstatus = 2
            } else {
                enterformstatus = 1
            }
            this.setState({
                itemlist,
                dataList: res,
                statusHtml: true,
                secondList,
                active,
                enterformstatus,
                carIsHideContact: res.carIsHideContact,
                entId: res.entId
            })
        })
    }

    handleClick(i) {
        let { itemlist } = this.state
        itemlist.forEach((item, key) => {
            if (i === key) {
                item.open = !item.open
            } else {
                item.open = false
            }
        })
        this.setState({
            itemlist
        })
    }
    onHandleFirst() {
        let { dataList, } = this.state
        this.handleFirst({ creatorContact: dataList.creatorContact })
    }

    //打开电话模态框
    handleFirst(item) {
        this.setState({
            itemtelphon: item.creatorContact
        }, () => {
            this.getTelphone()
        })
    }
    getTelphone() {
        const { itemtelphon, carIsHideContact, dataList } = this.state
        if (carIsHideContact === '1' && itemtelphon === dataList.creatorContact) {
            return Taro.showToast({
                title: '买家已隐藏联系方式',
                icon: 'none'
            })
        }
        this.setState({
            isShow: true
        })
    }

    //私聊
    handleSecode(item) {
        debugger
        if (window.bridge) {
            const { dataList } = this.state
            window.bridge.callHandler('IMChat', { 'tephone': item.creatorContact }, function responseCallback(res) { })
            sdk.setWechatInfo(item.creatorContact, 1, dataList.carDataModel)
        }
    }
    //发起订金担保
    handleThree(item) {
        sessionStorage.setItem('_earnObj', JSON.stringify(item))
        Taro.navigateTo({
            url: `/pages/earnestform/earnestform?id=${item.id}&qpid=${item.qpid}`
        })
    }
    //电话取消
    handleCancel() {
        this.setState({
            isShow: false
        })
    }
    //电话确认
    handleConfirm() {
        if (window.bridge) {
            let { itemtelphon } = this.state
            window.bridge.callHandler('call', { 'tephone': itemtelphon }, function responseCallback(res) { })
        }
    }

    async onHandleMoney() {
        // infoByEnterprise 这个接口如果返回空对象则说明是第一次进行过电子登记簿的开通，需要引导用户开通电子登记簿
        let accountInfo = await http.infoByEnterprise()
        const userInfo = await http.myselfDetail()
        let keys = Object.keys(accountInfo)

        if (!keys.length) {
            // 企业员工
            if (userInfo.imIdStatus == 2) {
                this.setState({
                    accContent: '本企业尚未开通企业收款账户，请联系企业管理员开通后再操作。',
                    imIdStatus: userInfo.imIdStatus
                })
            }
            this.setState({
                showAccDialog: true
            })
        } else {
            // 已经进行过开通
            if (accountInfo.status == '1') {
                // 电子登记簿开通审核中
                Taro.showToast({
                    title: '电子登记簿开通申请正在审核中，请耐心等待。',
                    icon: 'none'
                })
            } else if (accountInfo.status == '2') {
                // 审核被拒
                this.setState({
                    accContent: '电子登记簿开通申请被拒绝，是否重新开通？'
                })
            } else {
                // 审核通过
                this.setState({
                    isOpened: true
                })
            }
        }
    }

    bindCarform(key, value) {
        if (key) {
            if (key === 'money') {
                let Digit = common.getDigit(value, this.state._objMoney.money)
                this.setState({
                    _objMoney: Object.assign(this.state._objMoney, { [key]: Digit })
                })
            } else {
                this.setState({
                    _objMoney: Object.assign(this.state._objMoney, { [key]: value })
                })
            }

        }
    }

    onSubmit() {
        let { _objMoney, id, dataList } = this.state
        let indList = dataList
        let lPri = 0
        let nVal = this.state.oldVal
        let value = _objMoney.money
        if (!_objMoney['money']) {
            return Taro.showToast({
                title: '请填写报价金额!',
                icon: 'none'
            })
        }
        if (indList && indList.carGuiPrice) {
            lPri = indList.carGuiPrice

        }

        // 改价须在指导价的0.5-2倍之间
        if (value <= lPri * 2 && value >= lPri * 0.5) {
            nVal = value
        } else {

            Taro.showToast({
                title: "改价须在市场指导价的0.5-2倍之间",
                icon: 'none'
            })
            _objMoney['money'] = nVal
            this.setState({

                _objMoney
            })
            return
        }
        let _obj = {
            carDataModel: dataList.carDataModel,
            carId: id,
            carNo: dataList.carNo,
            creatorId: dataList.creatorId,
            qpPrice: _objMoney['money'],
            qpRemark: _objMoney['moneyback']
        }
        http.addUserMoney(_obj).then(() => {
            Taro.showToast({
                title: "已报价成功！",
                duration: 800,
                mask: true
            }).then(() => {
                this.setState({
                    isOpened: false
                }, () => {
                    this.getCarSearchDetail({ id: `${this.state.id}` })
                })
            })

        })
    }

    //终止寻车
    handStopSearch() {
        let { id } = this.state
        http.stopMySearchCarTakeOff({ id }).then(() => {
            Taro.showToast({
                title: '已终止寻车',
                duration: 800,
                mask: true
            }).then(() => {
                setTimeout(() => {
                    // Taro.navigateBack({
                    //     delta: 1
                    // })
                    Taro.redirectTo({
                        url: `/pages/index/index?active=1`
                    })
                }, 1000)
            })
        })
    }
    //删除车辆
    handDeleteCar() {
        let { id } = this.state
        http.delMySearchCar({ id }).then(() => {
            Taro.showToast({
                title: '已删除车辆',
                duration: 800,
                mask: true
            }).then(() => {
                setTimeout(() => {
                    Taro.navigateBack({
                        delta: 1
                    })
                }, 1000)
            })
        })
    }
    //跳转企业
    handleTocaompany() {
        let { entId } = this.state
        Taro.navigateTo({
            url: `/pages/companydetail/companydetail?id=${entId}`
        })
    }
    onCancel() {
        this.setState({
            showAccDialog: false
        })
    }
    onSure() {
        this.onCancel()
        if (this.state.imIdStatus != 2) {
            Taro.navigateTo({
                url: `/pages/accountBook/accountBook`
            })
        }
    }
    handleTagItem(id) {
        const { tagActives } = this.state
        const index = tagActives.findIndex(item => item == id)
        if (index !== -1) {
            tagActives.splice(index, 1)
        } else {
            tagActives.push(id)
        }
        this.setState({
            tagActives
        })
    }
    onOpenComplaint() {
        this.setState({
            showComplaint: true
        })
    }
    onCloseComplaint() {
        this.setState({
            showComplaint: false
        })
    }

    render() {
        const {
            itemlist,
            dataList,
            isShow,
            status,
            active,
            secondList,
            footerlist,
            isOpened,
            _objMoney,
            itemtelphon,
            enterformstatus,
            enterform,
            statusHtml,
            showAccDialog,
            accContent,
            imIdStatus,
            tags,
            showComplaint,
            tagActives
        } = this.state
        const list = [
            {
                name: '外观颜色',
                text: `${dataList.carOutColor || '---'}`
            },
            {
                name: '内饰颜色',
                text: `${dataList.carInColor || '---'}`
            },
            {
                name: '上牌地点',
                text: `${dataList.carTransAddrDetail || '---'}`
            },
            {
                name: '寻车状态',
                text: `${dataList.carSearchType || '---'}`
            },
            {
                name: '备注',
                text: `${dataList.carRemark || '(空)'}`
            }
        ]
        const _objDetail = function (value) {
            this.bindCarform(arguments[arguments.length - 1].bind, value)
        }
        return (
            statusHtml ? <View className='b_detail'>
                <DNavBar title={'寻车详情'}></DNavBar>
                <View className={classNames('b_detail__box', active === '2' ? 'b_detail__active' : '')}>
                    <View className='b_detail__box_header'>
                        <View className='b_detail__box_header__number'>
                            <Text className="item_number">编</Text>
                            <Text className='item_info'>{dataList.carNo || '---'}</Text>
                            <Image src={icon_complaint} className="icon_complaint" onClick={this.onOpenComplaint.bind(this)}></Image>
                        </View>
                        <View className='b_detail__box_header__name'>

                            <Text className="item_name">{dataList.carDataModel || '---'}</Text>
                        </View>
                        <View className='b_detail__box_header__info'>
                            <View className='item_info__left'>
                                <Text className='item_left'>{dataList.carSourceType}</Text>
                                <Text className='item_left'>{dataList.carEmissionStd}</Text>
                                <Text className='item_left'>
                                    {window.toFixed(dataList.carGuiPrice)}万/
								<Text>{countMinPri(dataList.carOfferPrice, dataList.carGuiPrice)}万
								</Text>
                                </Text>
                            </View>
                            {+dataList.carOfferPrice !== 0 && <View className='item_info__right'>期望报价：<Text className='item_right__text'>{window.toFixed(dataList.carOfferPrice) || '---'}万元</Text></View>}
                        </View>
                        {/* <View className='b_detail__box_money'>
                            <View className='b_detail__box_money__left'>市场指导价：{dataList.carGuiPrice}万元 </View>
                            <View className='b_detail__box_money__right'>期望报价：<Text className='item_right__text'>(缺少字段)万元</Text></View>
                    </View> */}
                        <View className='b_detail__box_header__time'>
                            <Text>{dataList.createTime}</Text>
                            <Text className='item_day__padding'>有效期：{dataList.carSearchValidity || '---'}天</Text>
                        </View>
                        <View className='b_detail__box_header__list'>
                            {

                                list.map((item, i) => {
                                    return <View className='item_list' key={i}>
                                        <View className='item_list__name'>{item.name}</View>
                                        <View className='item_list__text'>{item.text}</View>
                                    </View>
                                })
                            }
                        </View>
                    </View>
                    {
                        active === '2' && <View className='b_detail__box_userinfo'>
                            <Image className='b_detail__box_userinfo-img' src={enterform.img}></Image>
                            {
                                enterformstatus === 1 && <View className='b_detail__box_userinfo-text' onClick={this.handleTocaompany.bind(this)}>
                                    <View className='b_detail__box_userinfo-name'>{dataList.entName}</View>
                                    <View className='b_detail__box_userinfo-addre'>{dataList.entDis}</View>
                                    <View className='b_detail__box_userinfo-telphone'> 联系方式： {dataList.creatorContact || '---'}</View>
                                </View>
                            }
                            {
                                enterformstatus === 2 && <View className='b_detail__box_userinfo-text'>
                                    <View className='b_detail__box_userinfo-text1'>买家已隐藏联系方式</View>
                                    <View className='b_detail__box_userinfo-text2'>请直接报价，等待买家主动联系</View>
                                </View>
                            }
                        </View>
                    }

                    <View className='b_detail__box_content'>
                        <View className='b_detail__box_content__title'>已经有{dataList.carViewed}位商家查看、共有{itemlist.length || '0'}个报价</View>
                        {
                            active === '1' &&
                            <DUserlistBox list={itemlist}
                                handleClick={status !== '2' && this.handleClick.bind(this)}
                                onHandleFirst={this.handleFirst.bind(this)}
                                onHandleSecode={this.handleSecode.bind(this)}
                                onHandleThree={this.handleThree.bind(this)}
                            ></DUserlistBox>
                        }
                        {
                            active === '2' && <AtList>
                                {
                                    secondList && secondList.map(item => {
                                        return <AtListItem {...item}></AtListItem>
                                    })
                                }
                            </AtList>
                        }
                    </View>
                    {status === '1' && active === '1' &&
                        < View className='b_detail__box_btn'>
                            <AtButton className='item_btn' onClick={this.handStopSearch.bind(this)}>终止寻车</AtButton>
                        </View>
                    }

                    {status === '2' && active === '1' &&
                        < View className='b_detail__box_btn'>
                            <AtButton className='item_btn item_btn__default ' onClick={this.handDeleteCar.bind(this)}>删除车辆</AtButton>
                        </View>
                    }

                </View>
                {

                    active === '2' && <View className='b_detail__box_footer'>
                        <View className='b_detail__box_footer__list'>
                            <View className='b_detail__box_footer__btn'>
                                {
                                    footerlist && footerlist.map((item, i) => {
                                        return <View className=' b_detail__box_footer__item' onClick={item.onhandle}>
                                            <Image src={item.src} className='b_detail__box_footer__item-image'></Image>
                                            <View className='b_detail__box_footer__item-text'>{item.text}</View>
                                        </View>
                                    })
                                }
                            </View>
                            <View className='item_btn' onClick={this.onHandleMoney.bind(this)}>立即报价</View>
                        </ View>
                    </View>
                }
                <AtActionSheet isOpened={isOpened}>
                    <View className='b_detail__box_addmoney'>
                        <View className='b_detail__box_addmoney-title'>
                            <View className='b_detail__box_addmoney-cancel' onClick={() => { this.setState({ isOpened: false }) }}>取消</View>
                            <View className='b_detail__box_addmoney-text'>报价</View>
                            <View className='b_detail__box_addmoney-submit' onClick={this.onSubmit.bind(this)}>提交</View>
                        </View>
                        <DAtInpute onChange={_objDetail.bind(this)} bind='money' title='报价价格' type='number' value={_objMoney.money}>万</DAtInpute>
                        <DAtInpute onChange={_objDetail.bind(this)} bind='moneyback' title='留言' placeholder='可给经销商进行留言' value={_objMoney.moneyback}></DAtInpute>
                    </View>
                </AtActionSheet>
                <DModal
                    isShow={isShow}
                    title='提示'
                    text={`确认拨打${itemtelphon.substr(0, 3) + '-' + itemtelphon.substr(3, 4) + '-' + itemtelphon.substr(7, 4)}吗`}
                    onFirst={this.handleCancel.bind(this)}
                    onLast={this.handleConfirm.bind(this)}
                    onCancel={this.handleCancel.bind(this)}
                >
                </ DModal>
                <Ddialog isShow={showAccDialog} content={accContent} btnText={imIdStatus == 2 ? '我知道了' : '前往开通'} onCancel={this.onCancel.bind(this)} onSure={this.onSure.bind(this)}></Ddialog>

                <AtActionSheet className="action_sheet" isOpened={showComplaint}>
                    <View className="header">
                        <View className="title">投诉</View>
                        <Image src={icon_close} onClick={this.onCloseComplaint.bind(this)}></Image>
                    </View>
                    <View className="content">
                        <View className="tip">请选择投诉原因后进行提交～</View>
                        <View className="tags">
                            {
                                tags.map((item) => (
                                    <View className={['tag', tagActives.includes(item.id) ? 'active' : ''].join(' ')} onClick={this.handleTagItem.bind(this, item.id)}>{item.text}</View>
                                ))
                            }
                        </View>
                        <AtTextarea maxLength={120} placeholder="请输入投诉内容"></AtTextarea>
                        <AtButton className="submit" onClick={this.onCloseComplaint.bind(this)}>提交</AtButton>
                    </View>
                </AtActionSheet>
            </View> : ''
        )
    }
}
